﻿using System;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace HenhouseEnvironmentCtrl
{
    public partial class SetWarningForm : Form
    {
        public SetWarningForm()
        {
            InitializeComponent();
        }

        private void SetWarningForm_Load(object sender, EventArgs e)
        {
            LoadHenhouse();
        }

        private void LoadHenhouse()
        {
            SqlConnection conn = DBConnection.CreateConnection();
            DBConnection.Open(conn);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "SELECT * FROM Henhouse";
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                cboHenhouse.Items.Add(reader["HenhouseName"].ToString());
            }
            reader.Close();
            DBConnection.Close(conn);
        }

        private void BtnSetWarning_Click(object sender, EventArgs e)
        {
            if (cboHenhouse.SelectedItem == null)
            {
                MessageBox.Show("请选择鸡舍");
                return;
            }

            float tempMax, tempMin, humMax, humMin;
            int pm25Max, pm25Min, nh3Max, nh3Min, co2Max, co2Min;

            if (!float.TryParse(txtTempMax.Text, out tempMax) || !float.TryParse(txtTempMin.Text, out tempMin) ||
                !float.TryParse(txtHumMax.Text, out humMax) || !float.TryParse(txtHumMin.Text, out humMin) ||
                !int.TryParse(txtPM25Max.Text, out pm25Max) || !int.TryParse(txtPM25Min.Text, out pm25Min) ||
                !int.TryParse(txtNH3Max.Text, out nh3Max) || !int.TryParse(txtNH3Min.Text, out nh3Min) ||
                !int.TryParse(txtCO2Max.Text, out co2Max) || !int.TryParse(txtCO2Min.Text, out co2Min))
            {
                MessageBox.Show("请输入正确的数值");
                return;
            }

            SqlConnection conn = DBConnection.CreateConnection();
            DBConnection.Open(conn);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = $"UPDATE Henhouse SET TempMax={tempMax}, TempMin={tempMin}, HumMax={humMax}, HumMin={humMin}, PM25Max={pm25Max}, PM25Min={pm25Min}, NH3Max={nh3Max}, NH3Min={nh3Min}, CO2Max={co2Max}, CO2Min={co2Min} WHERE HenhouseName='{cboHenhouse.SelectedItem.ToString()}'";
            try
            {
                cmd.ExecuteNonQuery();
                MessageBox.Show("设置成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show("设置失败: " + ex.Message);
            }
            finally
            {
                DBConnection.Close(conn);
            }
        }
    }
}
